﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Savage.DotNetLibrary.BulkSmsLibrary
{
    public static class BulkSmsHttpApi
    {
        private const string url = "https://www.bulksms.co.uk/eapi/submission/send_sms/2/2.0";

        public static SendSmsStatus SendSms(SendSmsInfo sendSmsInfo)
        {
            Uri uri = new Uri(url);

            ProtocolLibrary.HttpWrapper httpWrapper = new ProtocolLibrary.HttpWrapper(uri);
            string response = httpWrapper.Post(GetPostData(sendSmsInfo));

            string[] values = response.Split('|');
            if (values.Length == 3 && values[2] != "\n")
                return new SendSmsStatus(int.Parse(values[0], CultureInfo.InvariantCulture), values[1], int.Parse(values[2], CultureInfo.InvariantCulture));
            else if (values.Length == 3)
                return new SendSmsStatus(int.Parse(values[0], CultureInfo.InvariantCulture), values[1]);
            else
                return new SendSmsStatus(-1, response);
        }

        public static string GetPostData(SendSmsInfo sendSmsInfo)
        {
            //username
            if (String.IsNullOrEmpty(sendSmsInfo.UserName))
                throw new ArgumentException("The parameter: username is null or empty.");
            //password
            if (String.IsNullOrEmpty(sendSmsInfo.Password))
                throw new ArgumentException("The parameter: password is null or empty.");
            //message
            if (String.IsNullOrEmpty(sendSmsInfo.Message))
                throw new ArgumentException("The parameter: message is null or empty.");

            //numbers
            if ((sendSmsInfo.Recipients.Count == 0) && (sendSmsInfo.Recipients.Count == 0))
                throw new ArgumentException("The parameter: Recipients and the parameter Recipients has no data.");


            StringBuilder queryString = new StringBuilder();
            queryString.Append("username=" + System.Web.HttpUtility.UrlEncode(sendSmsInfo.UserName, System.Text.Encoding.GetEncoding("ISO-8859-1")));
            queryString.Append("&password=" + System.Web.HttpUtility.UrlEncode(sendSmsInfo.Password, System.Text.Encoding.GetEncoding("ISO-8859-1")));
            queryString.Append("&message=" + System.Web.HttpUtility.UrlEncode(sendSmsInfo.Message, System.Text.Encoding.GetEncoding("ISO-8859-1")));
            if (sendSmsInfo.Recipients.Count > 0)
            {
                string value = "";
                foreach (string recipient in sendSmsInfo.Recipients)
                {
                    if (value.Length > 0)
                        value += ",";

                    value += System.Text.RegularExpressions.Regex.Replace(recipient, @"\D", "");
                }
                queryString.Append("&msisdn=" + value);
            }
            else
            {
                string value = "";
                foreach (int groupId in sendSmsInfo.GroupIds)
                {
                    if (value.Length > 0)
                        value += ",";

                    value += groupId.ToString(CultureInfo.InvariantCulture);
                }
                queryString.Append("&dest_group_id=" + value);
            }

            if (!String.IsNullOrEmpty(sendSmsInfo.Sender))
                queryString.Append("&sender=" + System.Web.HttpUtility.UrlEncode(sendSmsInfo.Sender, System.Text.Encoding.GetEncoding("ISO-8859-1")));

            if (sendSmsInfo.MessageClass != MessageClassOption.Default)
                queryString.Append("&msg_class=" + (int)sendSmsInfo.MessageClass);

            if (sendSmsInfo.DataCodingAlphabet != DataCodingAlphabetOption.Default)
                queryString.Append("&dca=" + sendSmsInfo.DataCodingAlphabet.ToString());

            if (sendSmsInfo.WantReport)
                queryString.Append("&want_report=1");

            if (sendSmsInfo.RoutingGroup != RoutingGroupOption.Default)
                queryString.Append("&routing_group=" + (int)sendSmsInfo.RoutingGroup);

            if (!String.IsNullOrEmpty(sendSmsInfo.SourceId))
                queryString.Append("&source_id=" + System.Web.HttpUtility.UrlEncode(sendSmsInfo.SourceId, System.Text.Encoding.GetEncoding("ISO-8859-1")));

            if (sendSmsInfo.Repliable != null)
            {
                if (sendSmsInfo.Repliable.Value)
                {
                    queryString.Append("&repliable=1");
                }
                else
                {
                    queryString.Append("&repliable=0");
                }
            }

            if (sendSmsInfo.StripDuplicateRecipients)
                queryString.Append("&strip_dup_recipients=1");

            if (sendSmsInfo.StopDupId != null)
                queryString.Append("&stop_dup_recipients=" + sendSmsInfo.StopDupId);

            if (sendSmsInfo.SendTime != null)
            {
                queryString.Append("&send_time=" + sendSmsInfo.SendTime.Value.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture));

                if (!String.IsNullOrEmpty(sendSmsInfo.SchedulingDescription))
                    queryString.Append("&scheduling_description=" + System.Web.HttpUtility.UrlEncode(sendSmsInfo.SchedulingDescription, System.Text.Encoding.GetEncoding("ISO-8859-1")));
            }

            //TODO: Add test success and fail querystrings in here
            bool allowConcatenation = sendSmsInfo.Message.Length > 160;
            if (allowConcatenation)
            {
                queryString.Append("&allow_concat_text_sms=1");

                sendSmsInfo.MaxConcatenatedMessageParts = (sendSmsInfo.Message.Length / 153) + 1;
                if (sendSmsInfo.MaxConcatenatedMessageParts != 2)
                    queryString.Append("&concat_text_sms_max_parts=" + sendSmsInfo.MaxConcatenatedMessageParts);
            }
            return queryString.ToString();
        }


    }
}
